package com.example.filter;

import com.example.pojo.MyResponseResult;
import com.example.utils.MyJwtUtils;
import com.example.utils.MyThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(urlPatterns = "/*")
@Component
public class MyLoginFilter implements Filter {

    @Autowired
    private MyJwtUtils myJwtUtils;

    // 这个方法在每次浏览器请求的时候,都会执行1次
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     //   System.out.println("浏览器请求了");
        /*
            1: 获取用户的请求路径,如果是 去登陆,直接放行
            2: 根据请求头 Token 获取令牌
            3: 校验令牌是否合法,如果合法则放行
            4: 如果不合法,则响应一个错误状态对象
         */
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if("/login".equals(uri)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token=request.getHeader("Token");
        Map<String,Object> map = myJwtUtils.parseJwt(token);
        if(map==null){
            MyResponseResult<Object> result = MyResponseResult.error("Not-Login");
            String jsonString = JSONObject.toJSONString(result);
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.getWriter().println(jsonString);
            return;
        }
        // 放行
        MyThreadLocalUtils.setValue(map);
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

